import 'whatwg-fetch';
import querystring from 'querystring';
const credentials = 'same-origin';

export default async (args) => {
  const p = {
    method: 'get',
    headers: {
      'Content-Type': 'application/json'
    },
    url: '',
    param: {},
    body: null,
    loading: true,
    ...args
  };

  if (p.loading) {

  }

  try {
    let f;
    if (p.method.toLowerCase() === 'get') {
      const query = Object.keys(p.param).length > 0 ? `?${querystring.stringify(p.param)}` : '';
      f = await fetch(`${p.url}${query}`, {
        headers: p.headers,
        credentials: credentials,
      }).catch(err => console.error(err));
    } else if (p.method.toLowerCase() === 'post') {
      f = await fetch(p.url, {
        method: 'POST',
        headers: p.headers,
        redirect: 'follow',
        body: p.body || JSON.stringify(p.param),
        credentials: credentials
      }).catch(err => console.error(err));
    } else {
      return false;
    }
    const jsonRes = await f.json().catch(err => console.error(err));
    if (jsonRes && jsonRes.code) {
      return jsonRes;
    } else {
      return { code: 403 };
    }
  } catch (ex) {
    console.log(`%c[${p.method} fail] ${p.url}`, `color:#f24040;font-weight:600;`);
    console.log(`%c${ex}`, `color:#f24040;font-weight:600;`);
  }

}
